import { Vec3 } from 'cc';
export class  GeometryTool  {
  public static isBallBetween(a: Vec3, b: Vec3, c: Vec3) {
    const minx = Math.min(a.x ,b.x);
    const maxx = Math.max(a.x ,b.x);
    const minz = Math.min(a.z, b.z);
    const maxz = Math.max(a.z, b.z);
    const th = 0.15;
    if (c.x > minx - th && c.x < maxx + th && c.z > minz - th && c.z < maxz + th) {
      return true;
    }

    return true;
  }

  public static isBetweenCollision(a: Vec3, b: Vec3, c: Vec3, ball: Vec3) {
    const minx = Math.min(a.x ,b.x);
    const maxx = Math.max(a.x ,b.x);
    const minz = Math.min(a.z, b.z);
    const maxz = Math.max(a.z, b.z);
    const th = 0.15;
    if (c.x > minx - th && c.x < maxx + th && c.z > minz - th && c.z < maxz + th) {
      return true;
    }

    const A = b.z - a.z;
    const B = a.x - b.x;
    const C = a.z * b.x - a.x * b.z;

    const dist = Math.abs(A * ball.x + B * ball.z + C) / Math.sqrt(A * A + B * B);

    if (dist > 1) return false;

    const xies = (b.x - ball.x) * (b.x - ball.x) + (b.z - ball.z) * (b.z - ball.z);
    const pd = xies - dist * dist;

    const abd = (a.x - b.x) * (a.x - b.x) + (a.z - b.z) * (a.z - b.z);

    return pd < abd + 0.01;
  }
  public static distanceXZ(a: Vec3, b: Vec3) {
    return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.z - b.z) * (a.z - b.z));
  }
  // C点 在A点和B点构造的线段上的投影
  public static projectSegmentPoint(a: Vec3, b: Vec3, c: Vec3, out: Vec3) {
    const dac = GeometryTool.distanceXZ(a, c);
    const dab = GeometryTool.distanceXZ(a, b);
    if (dac < 1 || dab < 1) {
      out.set(c);
      return out;
    }
    const costheta = ((c.x - a.x) * (b.x - a.x) + (c.z - a.z) * (b.z - a.z)) / (dac * dab);
    out.x = b.x - a.x;
    out.y = b.y - a.y;
    out.z = b.z - a.z;

    out = out.normalize().multiplyScalar(dac * costheta);

    out.x = a.x + out.x;
    out.y = a.y;
    out.z = a.z + out.z;

    return out;
  }
  public static distanceXZS(a: Vec3, b: Vec3) {
    return (a.x - b.x) * (a.x - b.x) + (a.z - b.z) * (a.z - b.z);
  }
}